import { useCallback, useEffect, useState } from 'react';
import { Form, Input, Space, Button } from 'antd';
import { TextWidget, getMessage } from '@inbiz/react';
import { GlobalRegistry } from '@inbiz/core';
import {
  langToDesignlKey,
  postMessage,
  getSiteLangType,
  uuidSmall,
} from '@inbiz/utils';
import { setAddLanguage, setEditLanguage } from '../service';
// @ts-ignore
import styles from '../index.less';

interface IAddParams {
  key: string;
  siteType: 1 | 2 | 4 | 7;
  kindItems: {
    kindName: string;
    kindCode: string;
    langText: string;
  }[];
}

interface EditFormProps {
  changeType: Function; // 改变浮层内容类型
  active?: any; // 当前选中多语言
  changeActive: Function; // 改变当前多语言
  appInfo: any;
  formid: string;
  langList: {
    // 当前系统语言列表
    KindName: string;
    KindCode: string;
  }[];
}

const EditForm = (props: EditFormProps) => {
  const { changeType, active, changeActive, langList, appInfo, formid } = props;

  // 保存时按钮loadding
  const [saveLoadding, $saveLoadding] = useState<boolean>(false);
  // 表单
  const [form] = Form.useForm();

  // 初始化表单
  useEffect(() => {
    let obj: any = {
      Key: uuidSmall(0, 36),
    };
    if (active) {
      obj.Key = active.Key;
      active.Kinds.map((item: any) => {
        obj[item.KindCode] = item.LangText;
      });
    }
    form.setFieldsValue(obj);
  }, []);

  // 提交添加多语言表单
  const addLanguage = useCallback(() => {
    form.validateFields().then((res: any) => {
      $saveLoadding(true);
      let locale: any = {};
      const obj: IAddParams = {
        key: res.Key,
        siteType: active?.SiteType || getSiteLangType(),
        kindItems: [],
      };
      langList.map((item: any) => {
        obj.kindItems.push({
          kindName: item.KindName,
          kindCode: item.KindCode,
          langText: res[item.KindCode],
        });
        locale[langToDesignlKey(item.KindCode)] = {
          global: {
            [res.Key]: res[item.KindCode],
          },
        };
      });
      const fn = active ? setEditLanguage : setAddLanguage;
      fn(obj, appInfo?.isWf, formid)
        .then((success: any) => {
          if (success === true) {
            let data: any = {
              Key: obj.key,
              siteType: obj.siteType,
              Kinds: [],
            };
            obj.kindItems.map((item: any) => {
              data.Kinds.push({
                KindName: item.kindName,
                KindCode: item.kindCode,
                LangText: item.langText,
              });
            });
            // 注册多语言（本地数据）
            GlobalRegistry.registerDesignerLocales(locale);
            $saveLoadding(false);
            changeActive(data);
            changeType('active');
            // VsCode环境下Message通讯
            postMessage({
              module: 'languageDesign',
              event: active ? 'edit' : 'add',
              data: {
                key: obj.key,
              },
            });
          } else {
            $saveLoadding(false);
          }
        })
        .catch(() => $saveLoadding(false));
    });
  }, [form, langList, active]);

  const only_key = getMessage('MultilingualInput.only_key'); // 唯一标识
  const rule_not_null = getMessage('MultilingualInput.rule_not_null'); // 不能为空
  const rule_type = getMessage('MultilingualInput.rule_type'); // 只能输入英文大小写、数字、下划线、中划线
  const rule_length = getMessage('MultilingualInput.rule_length'); // 长度不能超过16
  const rule_null = getMessage('MultilingualInput.rule_null'); // 首尾不能为空
  return (
    <>
      <div className={styles['add-form']}>
        {active ? (
          <p className={styles['edit-message']}>
            {/* 其他绑定此多语言的控件会同步变更 */}
            <TextWidget>MultilingualInput.edit_message</TextWidget>
          </p>
        ) : null}
        <Form form={form} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          <Form.Item
            name="Key"
            label={only_key}
            rules={[
              { required: true, message: rule_not_null }, // 不能为空
              { pattern: /^[0-9a-zA-Z_-]*$/, message: rule_type }, // 只能输入英文大小写、数字、下划线、中划线
              { max: 16, message: rule_length }, // 长度不能超过16
            ]}
          >
            <Input disabled />
          </Form.Item>
          {langList.map((item: any) => {
            return (
              <Form.Item
                key={item.KindCode}
                name={item.KindCode}
                label={item.KindName}
                rules={[
                  { required: true, message: `${rule_not_null}` }, // 不能为空
                  { pattern: /^(?!\s)(?!.*\s$)/, message: rule_null }, // 首尾不能为空
                ]}
              >
                <Input />
              </Form.Item>
            );
          })}
          <Form.Item wrapperCol={{ span: 24 }}>
            <Space align="end">
              <Button
                onClick={() => {
                  if (active) {
                    changeType('active');
                  } else {
                    changeType('list');
                  }
                }}
              >
                {/* 取消 */}
                <TextWidget>global.cancel</TextWidget>
              </Button>
              <Button
                type="primary"
                onClick={addLanguage}
                loading={saveLoadding}
              >
                {active ? (
                  <TextWidget>MultilingualInput.sure_edit</TextWidget>
                ) : (
                  <TextWidget>MultilingualInput.add_and_bind</TextWidget>
                )}{' '}
                {/* 确认修改 : 新增并绑定 */}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </>
  );
};

export default EditForm;
